import React, { useContext, useEffect, useRef, useState } from 'react';
import type { InputRef } from 'antd';
import { Button, Form, Input, Popconfirm, Table, Modal, Upload, message, Cascader } from 'antd';
import type { FormInstance } from 'antd/es/form';
import base from '@/utils/baseUrl'
import type { UploadChangeParam, RcFile, UploadFile, UploadProps } from 'antd/es/upload';
import {
    LoadingOutlined,
    PlusOutlined
} from '@ant-design/icons';
import { getAddress } from '@/request/common'
import CustomFrom from '@/components/CustomFrom'
import "./index.scss"
import { getUseridStoreInfo, addUseridStoreInfo, delUseridStoreInfo, updateUseridStoreInfo } from '@/request/store'

const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface Item {
    id?: React.Key;
    store_name?: string;
    area?: string;
    address?: string;
    logo?: string;
}

interface EditableRowProps {
    index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

interface EditableCellProps {
    title: React.ReactNode;
    editable: boolean;
    children: React.ReactNode;
    dataIndex: keyof Item;
    record: Item;
    handleSave: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
}) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef<InputRef>(null);
    const form = useContext(EditableContext)!;

    useEffect(() => {
        if (editing) {
            inputRef.current!.focus();
        }
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();

            toggleEdit();
            handleSave({ ...record, ...values });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };
    let childNode = children;
    if (editable) {
        childNode = editing ? (
            <Form.Item
                style={{ margin: 0 }}
                name={dataIndex}
                rules={[
                    {
                        required: true,
                        message: `${title} is required.`,
                    },
                ]}
            >
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
            <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
                {children}
            </div>
        );
    }
    return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];

interface DataType {
    id?: React.Key;
    store_name?: string;
    area?: string;
    address?: string;
    logo?: string;
    username?: string
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

const settleIn: React.FC = () => {
    const [dataSource, setDataSource] = useState<DataType[]>([]);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [open, setOpen] = useState(false);
    const formRef = useRef<FormInstance>(null)
    const [loading, setLoading] = useState(false);
    const [cascaderList, setCascaderList] = useState([])
    const [fromDate, setFromDate]: any = useState({})
    const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
        {
            title: '店铺名称',
            dataIndex: 'store_name',
            width: '30%',
            editable: true,
            render: (text: string) => {
                return <span>{text ? text : '/'}</span>
            }
        },
        {
            title: '选择地区',
            dataIndex: '',
            render: (record: any) => {
                return <Cascader style={{ width: '100%' }} allowClear onChange={(e) => areaChange(e, record)} defaultValue={record.area ? record.area.split('/') : []} fieldNames={{ label: 'name', value: 'name' }} options={cascaderList} placeholder="请选择地区" />
            }
        },
        {
            title: '详细地址',
            dataIndex: 'address',
            editable: true,
            render: (text: string) => {
                return <span>{text ? text : '/'}</span>
            }
        },
        {
            title: '店铺logo',
            dataIndex: '',
            key: 'logo',
            render: (record) => {
                return <div><Upload
                    name="file"
                    listType="picture-circle"
                    className="avatar-uploader2"
                    showUploadList={false}
                    action={base + '/upload'}
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                    data={{ type: 4, id: record.id }}
                    headers={{ "Authorization": localStorage.getItem('token') || '' }}
                >
                    {record.logo ? <img style={{ height: '50px', width: '50px', borderRadius: '50%' }} src={record.logo} alt="avatar" /> : uploadButton}
                </Upload></div>
            }
        },
        {
            title: '操作',
            dataIndex: '',
            key: 'op',
            render: (record: { id: React.Key }) =>
                dataSource.length >= 1 ? (
                    <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.id)}>
                        <a>删除</a>
                    </Popconfirm>
                ) : null,
        },
    ];
    useEffect(() => {
        getUseridStore()
    }, [])
    //获取店铺信息
    const getUseridStore = async () => {
        const res = await getUseridStoreInfo()
        const res2 = await getAddress()
        setCascaderList(res2.data)
        setDataSource(res.data)
    }
    const handleDelete = async (id: React.Key) => {
        await delUseridStoreInfo({ id: id })
        message.success('删除成功')
        getUseridStore()
    };
    const handleAdd = async () => {
        setOpen(true)
    };
    const areaChange = async (e: any, row: any) => {
        await updateUseridStoreInfo({
            area: e.join('/'),
            id: row.id
        })
    }
    const handleSave = async (row: DataType) => {
        const { username, ...info } = row
        await updateUseridStoreInfo(info)
        getUseridStore()
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: DataType) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
            }),
        };
    });
    const handleOk = () => {    //用户修改确定
        fromDate.submit()
        setConfirmLoading(true);
    };
    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getUseridStore()
        }
    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div>logo</div>
        </div>
    );
    const onFinish = async (value: any, errors: any[]) => {
        if (value.area) value.area = value.area.join('/')
        const res = await addUseridStoreInfo(value)
        if (res.status == 200) {
            message.success('添加成功')
            setConfirmLoading(false);
            setOpen(false)
            getUseridStore()
        }
        if (errors.length > 0) setConfirmLoading(false);
    }
    return (
        <div>
            <div className='flex flex-jc-fe'>
                <Button onClick={handleAdd} type="dashed" style={{ marginBottom: 16 }}>
                    添加店铺
                </Button>
            </div>
            <Table
                components={components}
                rowClassName={() => 'editable-row'}
                bordered
                dataSource={dataSource}
                rowKey='id'
                columns={columns as ColumnTypes}
            />
            <Modal
                title="店铺信息"
                open={open}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={() => setOpen(false)}
                width={'60%'}
                centered
            >
                <div style={{ margin: '20px 0' }}>
                    <CustomFrom
                        onFinish={onFinish}
                        selectList={cascaderList}
                        type={['area']}
                        getDom={(f: any) => { setFromDate(f) }} />
                </div>
            </Modal>
        </div>
    );
};
export default settleIn;